import router, { asyncRoutes } from './router'
import store from './store'
// 导入进度条插件
import NProgress from 'nprogress'
// 导入进度条样式
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'

// 白名单数组
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  // console.log('token', token)
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      next()
      if (!store.getters.name) {
        const menus = await store.dispatch('user/userInfoActions')
        const filterList = asyncRoutes.filter(routerObj => {
          const routerName = routerObj.children[0].name.toLowerCase()
          return menus.includes(routerName)
        })
        filterList.push({ path: '*', redirect: '/404', hidden: true })
        // addRoutes给路由表额外再增加一个规则对象
        router.addRoutes(filterList)
        store.commit('permission/setRoutes', filterList)
        next({
          path: to.path,
          replace: true
        })
      }
    }
  } else {
    asyncRoutes
    // 如果不存在 token，访问的是白名单内容，直接放行
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 没有 token，且不是白名单页面，跳转到登录页面
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  document.title = getPageTitle(to.meta.title)
  NProgress.done()
})
